#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <cerrno>
#include <cassert>
#include <string.h>
using namespace std;
// 父进程写入，子进程读取
int main()
{
    // 1.创建匿名管道
    int fd[2] = {0};
    int ret = pipe(fd);
    if (ret < 0)
    {
        cout << errno << ":" << strerror(errno) << endl;
    }
    // 2.创建子进程
    int n = fork();
    assert(n >= 0);
    if (n == 0)
    {
        // 子进程
        // 3.关闭不必要的fd
        close(fd[1]);
        // 4.开始通信
        int count=5;
        while (count--)
        {
            char buff[128];
            // cout<<"child:我在等待父进程发送的消息"<<endl;
            int n = read(fd[0], buff, 127);
            cout << "child:我等到了父进程发送的消息" << endl;
            if (n < 0)
            {
                cout << errno << ":" << strerror(errno) << endl;
                break;
            }
            if (n == 0)
            {
                cout << "I have already read the end of file" << endl;
                break;
            }
            buff[n] = '\0';
            cout << "child:";
            cout << buff << endl;
            sleep(1);
        }

        close(fd[0]);
        exit(0);
    }
    // 父进程
    // 3.关闭不必要的fd
    close(fd[0]);
    // 4.开始通信
    int message = 0;
    while (true)
    {
        char buff[128];
        cout << "parent:I am the parent process,I am preparing for write to the child" << endl;
        snprintf(buff, 128, "The parent process  writes message to my me:%d\n", message++);

        int n = write(fd[1], buff, strlen(buff));
        if (n < 0)
        {
            cout << errno << ":" << strerror(errno) << endl;
            break;
        }
        sleep(1);
    }

    close(fd[1]);
    return 0;
}